<?php
namespace Endpoints\Tools;

use Endpoints\Base\Endpoint;
use OSS\Core\OssException;
use OSS\OssClient;
use Symfony\Component\Console\Input\InputArgument;
class UploadOssObject extends Endpoint
{
    const ARGUMENT_FILE_NAME  = 'fileName';
    const ARGUMENT_FILE_PATH  = 'filePath';
    const ARGUMENT_SAVE_YEAR  = 'year';
    const ARGUMENT_SAVE_MONTH = 'month';
    const ARGUMENT_SAVE_DAY   = 'day';
    const ARGUMENT_PREFIX     = 'prefix';

    // 收参
    public function getArguments()
    {
        return [
            [static::ARGUMENT_FILE_NAME,InputArgument::REQUIRED,'文件名称',''],
            [static::ARGUMENT_FILE_PATH,InputArgument::REQUIRED,'文件路径',''],
            [static::ARGUMENT_PREFIX,InputArgument::OPTIONAL,'路径前缀',''],
            [static::ARGUMENT_SAVE_YEAR,InputArgument::OPTIONAL,'年份',date('Y')],
            [static::ARGUMENT_SAVE_MONTH,InputArgument::OPTIONAL,'月份',date('m')],
            [static::ARGUMENT_SAVE_DAY,InputArgument::OPTIONAL,'日期',date('d')],
        ];
    }

    /**
     * 实现逻辑
     */
    public function dryRun()
    {
        $fileName    = $this->argument(static::ARGUMENT_FILE_NAME);
        $filePath    = $this->argument(static::ARGUMENT_FILE_PATH);
        $saveYear    = $this->argument(static::ARGUMENT_SAVE_YEAR);
        $saveMonth   = $this->argument(static::ARGUMENT_SAVE_MONTH);
        $saveDay     = $this->argument(static::ARGUMENT_SAVE_DAY);
        $savePrefix  = $this->argument(static::ARGUMENT_PREFIX);
        $accessId     = env("ALIYUN_OSS_ID");
        $accessSecret = env("ALIYUN_OSS_SECRET");
        $endpoint     = "https://oss-cn-beijing.aliyuncs.com/";
        $bucket       = "candy2019";
        $objName      = $saveYear.'/'.$saveMonth.'/'.$saveDay.'/'.$fileName;
        if(!empty($savePrefix)){
            $objName = trim($savePrefix,'/').'/'.$objName;
        }
        try{
            $ossClient = new OssClient($accessId, $accessSecret, $endpoint);
            $putStatus = $ossClient->uploadFile($bucket,$objName,$filePath);
            if(isset($putStatus['info']['http_code']) && $putStatus['info']['http_code'] == 200){
                return $objName;
            }else{
                return '';
            }
        } catch(OssException $e) {
            return '';
        }

    }
}